package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ModelConfigMapper;
import com.zenithmind.chat.pojo.entity.ModelConfig;
import com.zenithmind.chat.pojo.query.ModelConfigQuery;
import com.zenithmind.chat.service.ModelConfigService;
import com.zenithmind.common.result.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI模型配置服务实现类
 */
@Service
public class ModelConfigServiceImpl extends ServiceImpl<ModelConfigMapper, ModelConfig> implements ModelConfigService {

    @Override
    public List<ModelConfig> getAllModels() {
        // 获取所有启用的模型
        LambdaQueryWrapper<ModelConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ModelConfig::getEnabled, 1)
              .orderByAsc(ModelConfig::getSortOrder);
        return this.list(wrapper);
    }

    @Override
    public List<ModelConfig> getAllEnabledModels() {
        // 实现与getAllModels相同，获取所有启用的模型
        return getAllModels();
    }

    @Override
    public List<ModelConfig> getModelsByType(Integer modelType) {
        // 获取指定类型的启用模型
        LambdaQueryWrapper<ModelConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ModelConfig::getModelType, modelType)
              .eq(ModelConfig::getEnabled, 1)
              .orderByAsc(ModelConfig::getSortOrder);
        return this.list(wrapper);
    }

    @Override
    public List<ModelConfig> getEnabledModelsByType(Integer modelType) {
        // 实现与getModelsByType相同，获取指定类型的启用模型
        return getModelsByType(modelType);
    }

    @Override
    public PageResult<ModelConfig> getModelPage(ModelConfigQuery query) {
        Page<ModelConfig> page = query.toPage();
        LambdaQueryWrapper<ModelConfig> wrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        wrapper.like(StringUtils.hasText(query.getModelName()), ModelConfig::getModelName, query.getModelName())
               .like(StringUtils.hasText(query.getDisplayName()), ModelConfig::getDisplayName, query.getDisplayName())
               .eq(query.getModelType() != null, ModelConfig::getModelType, query.getModelType())
               .eq(query.getEnabled() != null, ModelConfig::getEnabled, query.getEnabled());
        
        wrapper.orderByAsc(ModelConfig::getModelType)
              .orderByAsc(ModelConfig::getSortOrder);
        
        page = this.page(page, wrapper);
        return PageResult.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public ModelConfig getConfigById(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean addModel(ModelConfig modelConfig) {
        // 校验必填字段
        validateModelConfig(modelConfig);
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        modelConfig.setCreateTime(now);
        modelConfig.setUpdateTime(now);
        
        // 设置默认值
        if (modelConfig.getEnabled() == null) {
            modelConfig.setEnabled(1);
        }
        if (modelConfig.getSortOrder() == null) {
            // 获取当前最大排序值
            LambdaQueryWrapper<ModelConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(ModelConfig::getSortOrder)
                  .last("LIMIT 1");
            ModelConfig lastModel = this.getOne(wrapper);
            if (lastModel != null) {
                modelConfig.setSortOrder(lastModel.getSortOrder() + 10);
            } else {
                modelConfig.setSortOrder(10);
            }
        }
        
        return this.save(modelConfig);
    }

    @Override
    public boolean updateModel(ModelConfig modelConfig) {
        // 校验必填字段
        validateModelConfig(modelConfig);
        
        // 校验ID
        if (modelConfig.getId() == null) {
            throw new RuntimeException("模型ID不能为空");
        }
        
        // 检查模型是否存在
        ModelConfig existModel = this.getById(modelConfig.getId());
        if (existModel == null) {
            throw new RuntimeException("模型不存在");
        }
        
        // 更新时间
        modelConfig.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(modelConfig);
    }

    @Override
    public boolean saveOrUpdateConfig(ModelConfig modelConfig) {
        if (modelConfig.getId() != null) {
            return updateModel(modelConfig);
        } else {
            return addModel(modelConfig);
        }
    }

    @Override
    public boolean deleteModel(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean deleteConfig(Long id) {
        return deleteModel(id);
    }

    @Override
    public boolean toggleModelStatus(Long id, Integer enabled) {
        // 检查模型是否存在
        ModelConfig model = this.getById(id);
        if (model == null) {
            return false;
        }
        
        // 更新状态
        model.setEnabled(enabled);
        model.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(model);
    }

    @Override
    public boolean updateModelStatus(Long id, Integer enabled) {
        return toggleModelStatus(id, enabled);
    }

    @Override
    @Transactional
    public boolean deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return this.removeByIds(ids);
    }

    @Override
    @Transactional
    public boolean saveOrUpdateBatchConfig(List<ModelConfig> modelConfigs) {
        if (modelConfigs == null || modelConfigs.isEmpty()) {
            return false;
        }
        for (ModelConfig modelConfig : modelConfigs) {
            validateModelConfig(modelConfig); // 校验每个配置
            LocalDateTime now = LocalDateTime.now();
            if (modelConfig.getId() == null) { // 新增
                modelConfig.setCreateTime(now);
            }
            modelConfig.setUpdateTime(now);
        }
        return this.saveOrUpdateBatch(modelConfigs);
    }
    
    /**
     * 校验模型配置必填字段
     */
    private void validateModelConfig(ModelConfig modelConfig) {
        if (modelConfig.getModelType() == null) {
            throw new RuntimeException("模型类型不能为空");
        }
        if (!StringUtils.hasText(modelConfig.getModelName())) {
            throw new RuntimeException("模型名称不能为空");
        }
        if (!StringUtils.hasText(modelConfig.getDisplayName())) {
            throw new RuntimeException("显示名称不能为空");
        }
        if (!StringUtils.hasText(modelConfig.getApiUrl())) {
            throw new RuntimeException("API地址不能为空");
        }
    }
} 